import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { toast } from 'sonner';
import { useTheme } from '@/hooks/useTheme';
import { cn } from '@/lib/utils';

// 购物车商品接口
interface CartItem {
  id: string;
  productId: string;
  title: string;
  price: number;
  quantity: number;
  image: string;
  selected: boolean;
}

// 模拟购物车数据
const mockCartItems: CartItem[] = [
  {
    id: 'cart-1',
    productId: '1',
    title: '九成新 MacBook Pro 2023',
    price: 8999,
    quantity: 1,
    image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=laptop%20macbook%20pro%20new%20condition&sign=20f4f73de7dc224e47978f4a391ca9b9',
    selected: true
  },
  {
    id: 'cart-2',
    productId: '2',
    title: '大学英语四级词汇书',
    price: 25,
    quantity: 2,
    image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=english%20vocabulary%20book%20for%20exam&sign=69084fa9b4b4f62bc00931f403d1340b',
    selected: true
  },
  {
    id: 'cart-3',
    productId: '4',
    title: '篮球装备套装',
    price: 199,
    quantity: 1,
    image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=basketball%20equipment%20set%20with%20ball%20and%20shoes&sign=c7c0864626ca8ad7c63c6063a27ea339',
    selected: false
  }
];

export default function Cart() {
  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const [selectAll, setSelectAll] = useState(false);
  const { theme } = useTheme();

  // 加载购物车数据
  useEffect(() => {
    // 模拟API请求
    setTimeout(() => {
      setCartItems(mockCartItems);
      // 检查是否所有商品都已选中
      const allSelected = mockCartItems.every(item => item.selected);
      setSelectAll(allSelected);
    }, 500);
  }, []);

  // 切换商品选中状态
  const toggleItemSelection = (id: string) => {
    const updatedItems = cartItems.map(item => 
      item.id === id ? { ...item, selected: !item.selected } : item
    );
    setCartItems(updatedItems);
    // 检查是否所有商品都已选中
    const allSelected = updatedItems.every(item => item.selected);
    setSelectAll(allSelected);
  };

  // 全选/取消全选
  const handleSelectAll = () => {
    const updatedItems = cartItems.map(item => ({
      ...item,
      selected: !selectAll
    }));
    setCartItems(updatedItems);
    setSelectAll(!selectAll);
  };

  // 更新商品数量
  const updateQuantity = (id: string, change: number) => {
    const updatedItems = cartItems.map(item => {
      if (item.id === id) {
        const newQuantity = Math.max(1, item.quantity + change);
        return { ...item, quantity: newQuantity };
      }
      return item;
    });
    setCartItems(updatedItems);
  };

  // 删除商品
  const removeItem = (id: string) => {
    const updatedItems = cartItems.filter(item => item.id !== id);
    setCartItems(updatedItems);
    toast.success('商品已从购物车移除');
  };

  // 计算选中商品的总金额和总数量
  const selectedItems = cartItems.filter(item => item.selected);
  const totalQuantity = selectedItems.reduce((sum, item) => sum + item.quantity, 0);
  const totalPrice = selectedItems.reduce((sum, item) => sum + (item.price * item.quantity), 0);

  return (
    <div className={cn("min-h-screen bg-gray-50 dark:bg-gray-900 py-8 px-4 sm:px-6 lg:px-8")}>
      <div className="max-w-5xl mx-auto">
        <div className="flex items-center justify-between mb-6">
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">我的购物车</h1>
          <Link
            to="/"
            className="text-indigo-600 dark:text-indigo-400 hover:text-indigo-500 dark:hover:text-indigo-300 text-sm font-medium"
          >
            <i className="fa-solid fa-arrow-left mr-1"></i>
            继续购物
          </Link>
        </div>
        
        {cartItems.length === 0 ? (
          // 空购物车状态
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-8 text-center">
            <div className="inline-flex items-center justify-center p-6 rounded-full bg-gray-100 dark:bg-gray-700 mb-4">
              <i className="fa-solid fa-cart-shopping text-3xl text-gray-400"></i>
            </div>
            <h3 className="text-xl font-medium text-gray-900 dark:text-white mb-2">购物车还是空的</h3>
            <p className="text-gray-500 dark:text-gray-400 mb-6">
              快去挑选心仪的商品吧
            </p>
            <Link
              to="/"
              className="px-6 py-2 rounded-lg text-white bg-indigo-600 dark:bg-indigo-500 hover:bg-indigo-700 dark:hover:bg-indigo-600 text-sm font-medium"
            >
              立即购物
            </Link>
          </div>
        ) : (
          <div className="space-y-6">
            {/* 购物车商品列表 */}
            <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm overflow-hidden">
              <div className="grid grid-cols-12 gap-4 px-6 py-4 border-b border-gray-200 dark:border-gray-700 text-sm font-medium text-gray-500 dark:text-gray-400">
                <div className="col-span-7 flex items-center">
                  <input
                    type="checkbox"
                    checked={selectAll}
                    onChange={handleSelectAll}
                    className="h-4 w-4 text-indigo-600 dark:text-indigo-400 focus:ring-indigo-500 border-gray-300 dark:border-gray-600 rounded"
                  />
                  <span className="ml-2">全选</span>
                </div>
                <div className="col-span-2 text-center">单价</div>
                <div className="col-span-2 text-center">数量</div>
                <div className="col-span-1 text-center">操作</div>
              </div>
              
              {cartItems.map((item) => (
                <div 
                  key={item.id} 
                  className="grid grid-cols-12 gap-4 px-6 py-4 border-b border-gray-100 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors"
                >
                  <div className="col-span-7 flex items-center">
                    <input
                      type="checkbox"
                      checked={item.selected}
                      onChange={() => toggleItemSelection(item.id)}
                      className="h-4 w-4 text-indigo-600 dark:text-indigo-400 focus:ring-indigo-500 border-gray-300 dark:border-gray-600 rounded"
                    />
                    <div className="ml-4 flex items-center">
                      <div className="w-20 h-20 flex-shrink-0 bg-gray-100 dark:bg-gray-700 rounded-lg overflow-hidden">
                        <img 
                          src={item.image} 
                          alt={item.title}
                          className="w-full h-full object-cover"
                        />
                      </div>
                      <div className="ml-4">
                        <Link 
                          to={`/product/${item.productId}`}
                          className="text-sm font-medium text-gray-900 dark:text-gray-100 hover:text-indigo-600 dark:hover:text-indigo-400 line-clamp-2"
                        >
                          {item.title}
                        </Link>
                      </div>
                    </div>
                  </div>
                  
                  <div className="col-span-2 flex items-center justify-center">
                    <span className="text-sm font-medium text-gray-900 dark:text-gray-100">
                      ¥{item.price}
                    </span>
                  </div>
                  
                  <div className="col-span-2 flex items-center justify-center">
                    <div className="flex items-center border border-gray-300 dark:border-gray-600 rounded-lg">
                      <button
                        onClick={() => updateQuantity(item.id, -1)}
                        disabled={item.quantity <= 1}
                        className="px-2 py-1 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 disabled:opacity-50"
                      >
                        <i className="fa-solid fa-minus text-xs"></i>
                      </button>
                      <span className="px-2 text-sm font-medium text-gray-900 dark:text-gray-100 min-w-[40px] text-center">
                        {item.quantity}
                      </span>
                      <button
                        onClick={() => updateQuantity(item.id, 1)}
                        className="px-2 py-1 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"
                      >
                        <i className="fa-solid fa-plus text-xs"></i>
                      </button>
                    </div>
                  </div>
                  
                  <div className="col-span-1 flex items-center justify-center">
                    <button
                      onClick={() => removeItem(item.id)}
                      className="text-gray-500 dark:text-gray-400 hover:text-red-600 dark:hover:text-red-400"
                    >
                      <i className="fa-solid fa-trash-can"></i>
                    </button>
                  </div>
                </div>
              ))}
            </div>
            
            {/* 结算区域 */}
            <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-6 sticky bottom-0">
              <div className="flex flex-col md:flex-row items-center justify-between">
                <div className="flex items-center mb-4 md:mb-0">
                  <span className="text-sm text-gray-600 dark:text-gray-400 mr-4">
                    已选 <span className="font-medium text-gray-900 dark:text-gray-100">{totalQuantity}</span> 件商品
                  </span>
                  <button
                    onClick={() => {
                      const updatedItems = cartItems.filter(item => !item.selected);
                      setCartItems(updatedItems);
                      setSelectAll(false);
                      toast.success('已清空选中商品');
                    }}
                    disabled={selectedItems.length === 0}
                    className={`text-sm ${
                      selectedItems.length > 0 
                        ? 'text-red-600 dark:text-red-400 hover:text-red-500 dark:hover:text-red-300' 
                        : 'text-gray-400 cursor-not-allowed'
                    }`}
                  >
                    <i className="fa-solid fa-trash-can mr-1"></i>
                    清空选中
                  </button>
                </div>
                
                <div className="flex items-center space-x-4">
                  <div className="text-right">
                    <div className="text-sm text-gray-600 dark:text-gray-400">
                      合计: 
                      <span className="font-bold text-2xl text-red-600 dark:text-red-400 ml-2">
                        ¥{totalPrice.toFixed(2)}
                      </span>
                    </div>
                    <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                      已优惠 ¥0.00
                    </div>
                  </div>
                  
                  <button
                    disabled={selectedItems.length === 0}
                    className={`px-6 py-3 rounded-lg text-white font-medium ${
                      selectedItems.length > 0 
                        ? 'bg-indigo-600 dark:bg-indigo-500 hover:bg-indigo-700 dark:hover:bg-indigo-600' 
                        : 'bg-gray-300 dark:bg-gray-600 cursor-not-allowed'
                    }`}
                  >
                    去结算
                  </button>
                </div>
              </div>
            </div>
            
            {/* 猜你喜欢 */}
            <div className="mt-8">
              <h2 className="text-lg font-bold text-gray-900 dark:text-white mb-4">猜你喜欢</h2>
              
              <div className="grid grid-cols-2 sm:grid-cols-4 md:grid-cols-5 gap-4">
                {[1, 2, 3, 4, 5].map((item) => (
                  <div 
                    key={item} 
                    className="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden cursor-pointer hover:shadow-md transition-all"
                  >
                    <div className="h-32 overflow-hidden">
                      <img 
                        src={`https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=secondhand%20book%20${item}`} 
                        alt={`推荐商品 ${item}`}
                        className="w-full h-full object-cover"
                      />
                    </div>
                    <div className="p-2">
                      <h3 className="font-medium text-gray-900 dark:text-white text-xs line-clamp-2">
                        二手书籍 {item} 大学教材参考资料
                      </h3>
                      <div className="mt-1">
                        <span className="text-xs font-bold text-indigo-600 dark:text-indigo-400">
                          ¥{30 + item * 5}
                        </span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}